<?php

defined('BR') OR define('BR', "\n");

/**
 * 后台进程:订单
 * @property Order_queue_mdl $orderQueue
 * @property Order_mdl $order
 * @property Order_queue_finish_mdl $finishOrderQueue
 */
class Order extends Bg_Controller {
	
	private $workOrderList = array();
	
	const BUY_EXP = 3;//买水超时时间
	
	public function __construct() {
		set_time_limit(0);
		parent::__construct ();
		$this->load->model('Order_mdl','order');
		$this->load->model('Order_queue_mdl','orderQueue');
	}
	/**
	 * 启动监听订单队列进程
	 */
	public function index(){
		$startTime = time();
		$list  = array();
		$count = 0;
		while (TRUE) {
			$list = $this->orderQueue->find();
			$count = count($list);
			echo '.'.$count;
			if ( $count == 0 ) {
				if ( time() - $startTime > 300  ) {
					exit;
				}
				sleep(3);
			}else{
				$this->checkOrders($list);
				sleep(1);
			}
		}
		
	}
	
	public function checkOrders($list){
		// 以每次通知时的服务器端时间戳判断是否超时
		// 超时则以APP端的时间戳结算
		$now = time();
		foreach ($list as $order){
			$serverTime     = (float) $order['serverTime']; // 每次通知时服务器端的时间戳
			// 检查是否超时
			$diff = $now - $serverTime;
			if (  $diff >= 0 && $diff < self::BUY_EXP ) {
				continue;
			}
			// 超时则处理
			$orderID        = (int)   $order['_id'];
			$appTime        = (float) $order['appTime'];// 每次通知时APP端的时间戳
			
			$result = $this->order->end($orderID, $appTime+3);
			$isDequeue = $this->orderQueue->removeOneByID($orderID);
			$this->log( get_defined_vars() );
		}// end foreach($list)============
	}
	
	public function buy(){
		// 获取订单列表
		$list = $this->orderQueue->find();
		if ( ! empty($list) ) {
			echo '.'.count($list).'.';
		}
		foreach ($list as $order){
			$currTime = time();
			// 检查通知是否超时
			if( $currTime - $order['lastNotifyTime'] <= self::BUY_EXP ){
				continue;
			}
			// 超时则处理
			$state   = (int)$order['state'];
			$orderID = (int)$order['_id'];
			$lastNotifyTime = $order['lastNotifyTime'];
			switch ($state){
				case 2://开始取水:按3秒算钱,关闭订单
				case 3://出水中:按已有时长+3秒算钱,关闭订单
					$res = $this->order->end($orderID, $lastNotifyTime+3);
					$this->log($orderID, $state, $currTime, $res);
					break;
				case 4://取水结束:转移订单
					$this->orderQueue->removeOneByID($orderID);
			}
		
		}
		echo mt_rand(0, 9)==5 ? '.' : '';
		// 变量回收
		$list  = NULL;
		$order = NULL;
		$res   = NULL;
	}
	
	public function close(){
		$this->load->database();
		$i=10;
		while (($i--) >0) {
			$sql = 'UPDATE `hs_order_'.$i.'` SET isFinish=1 WHERE isFinish=0 AND createTime < (UNIX_TIMESTAMP(NOW())-120)';
			$res = $this->db->query($sql);
			echo $res,"\t",$this->db->affected_rows(),"\t",$sql,"\n";
		}
	}	
	
	
	
	
	
	private function log($vars){
		unset($vars['list']);
		unset($vars['order']);
		unset($vars['now']);
		foreach ( array('serverTime','appTime') as $key ){
			if ( isset($vars[$key]) ) {
				$vars[$key] = date('y-m-d H:i:s',$vars[$key]);
			}
		}
		echo PHP_EOL,json_encode($vars),PHP_EOL;
	}
	
}

